package com.egao.common.core.damon.baiduword.service;

import com.egao.common.core.damon.baiduword.utils.Base64Util;
import com.egao.common.core.damon.baiduword.utils.FileUtil;
import com.egao.common.core.damon.baiduword.utils.HttpUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

/**
 * @Date 2020/8/29 21:42
 * @Created by Damon
 */
public class BdWordService {
    /**
     * 普通识别文字
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     * 上传的图片使用JPG格式可以一定程度上提高识别准确率！
     */
    public String generalBasic(Map<String, String> requestMap) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        try {
            // 本地文件路径
//            String filePath = "C:\\Users\\damon\\Desktop\\2.jpg";
//            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String filePath = requestMap.get("PicUrl");
            File file = getFileByUrl(filePath, "jpg");
            byte[] imgData = FileUtil.readFile(file);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            BaiduWordAccessToken bdwat = new BaiduWordAccessToken();

            String result = HttpUtil.post(url, bdwat.getAccessToken(), param);
//            System.out.println(result);
            JSONObject jsonObject = JSONObject.fromObject(result);
            JSONArray jsonArray = jsonObject.getJSONArray("words_result");
            Iterator<JSONObject> it = jsonArray.iterator();
            StringBuilder sb = new StringBuilder();
            while (it.hasNext()) {
                JSONObject next = it.next();
                sb.append(next.get("words"));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 高精度识别文字
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public String accurate(Map<String, String> requestMap) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate";
        try {
            // 本地文件路径
//            String filePath = "C:\\Users\\damon\\Desktop\\2.jpg";
//            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String filePath = requestMap.get("PicUrl");
            File file = getFileByUrl(filePath, "jpg");
            byte[] imgData = FileUtil.readFile(file);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            BaiduWordAccessToken bdwat = new BaiduWordAccessToken();

            String result = HttpUtil.post(url, bdwat.getAccessToken(), param);
//            System.out.println(result);
            JSONObject jsonObject = JSONObject.fromObject(result);
            JSONArray jsonArray = jsonObject.getJSONArray("words_result");
            Iterator<JSONObject> it = jsonArray.iterator();
            StringBuilder sb = new StringBuilder();
            while (it.hasNext()) {
                JSONObject next = it.next();
                sb.append(next.get("words"));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public File getFileByUrl(String fileUrl, String suffix) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream stream = null;
        InputStream inputStream = null;
        File file = null;
        try {
            URL imageUrl = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            file = File.createTempFile("damon", "." + suffix);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(outStream.toByteArray());
        } catch (Exception e) {
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (stream != null) stream.close();
                outStream.close();
            } catch (Exception e) {
            }
        }
        return file;
    }

    public static void main(String[] args) {
        BdWordService bdWordService = new BdWordService();
        bdWordService.generalBasic(null);
    }
}
